﻿
namespace MetaVideoEditorEvolved.ViewModel
{
	using GalaSoft.MvvmLight.Threading;
	using MetaVideoEditorEvolved.Entity;
	using System;
	using System.Collections.Generic;
	using System.Linq;
	using System.Text;
	using System.Collections.ObjectModel;
	using mveEngine;
	using System.ComponentModel;
	using System.Windows.Input;
	using GalaSoft.MvvmLight.Command;
	using System.Diagnostics;
	using MetaVideoEditorEvolved.Messages;
	using GalaSoft.MvvmLight.Messaging;
	using GalaSoft.MvvmLight;
	using MetaVideoEditorEvolved.UI;

	public class SearchVM : ViewModelBase
	{
		private ObservableCollection<ManualSearchResultItem> searchResults = new ObservableCollection<ManualSearchResultItem>();

		private string titleSearch;
		
		private MetaVideoEditorEvolved.Helper.KernelHelper kernelHelper = new MetaVideoEditorEvolved.Helper.KernelHelper();

		private BackgroundWorker backgroundWorker = new BackgroundWorker();

		private MetaVideoEditorEvolved.UI.Entity.VideoMediaElement currentItem;
		private ManualSearchResultItem searchResultSelected;

		public SearchVM(MetaVideoEditorEvolved.UI.Entity.VideoMediaElement item)
		{
			currentItem = item;

			TitleSearch = item.Title;

			SearchCommand = new RelayCommand(() =>
			                                 {
			                                 	SearchMedia();
			                                 },
			                                 () =>
			                                 {
			                                 	return !string.IsNullOrEmpty(TitleSearch);
			                                 });

			new WaitingWindow(new Action(() =>
			                             {
			                             	Item itemToSearch = new Item { Title = TitleSearch};
			                             	if (item is MetaVideoEditorEvolved.UI.Entity.MediaItemBaseEntity) {
			                             		itemToSearch.Type = MetaVideoEditorEvolved.UI.Helper.EntityUiHelper.RetrieveEntityType(item);
			                             	}
			                             	
			                             	SearchResults = new ObservableCollection<ManualSearchResultItem>(from i in ProvidersUtil.FindPossible(itemToSearch)
			                             	                                                                 select new ManualSearchResultItem
			                             	                                                                 {
			                             	                                                                 	ResultItem = i,
			                             	                                                                 	IsChecked = false
			                             	                                                                 });
			                             }), string.Empty).ShowDialog();
			
			ConfirmResultCommand =new RelayCommand(() =>
			                                       {
			                                       	Item i = ProvidersUtil.MultiFetch((from res in SearchResults
			                                       	                                   where res.IsChecked == true
			                                       	                                   select res.ResultItem).ToList());
			                                       	
			                                       	var oldItem = MetaVideoEditorEvolved.UI.KernelSessionManager.SessionInstance.RealKernel.ItemCollection.ItemsList.First(media=>media.Id == item.Id.ToString());
			                                       	var newItem = mveEngine.Helper.UpdateItem(oldItem, i);
			                                       	this.kernelHelper.SyncItemToEngine(newItem);
			                                       	
			                                       	DispatcherHelper.UIDispatcher.Invoke(new Action(()=>
			                                       	                                                {
			                                       	                                                	newItem.CopyToMediaUiEntity(currentItem);
			                                       	                                                	currentItem.IsCheckedForUpdate = true;
			                                       	                                                	currentItem.HasChanged = true;
			                                       	                                                }));
			                                       	
			                                       	Messenger.Default.Send<CloseMessage>(new CloseMessage { WindowToClose = WindowType.Search });
			                                       },
			                                       () =>
			                                       {
			                                       	return (from i in SearchResults
			                                       	        where i.IsChecked == true
			                                       	        select i).Any();
			                                       });
		}

		public void UpdateItemSelected()
		{
			new WaitingWindow(new Action(() =>
			                             {
			                             	Item i = ProvidersUtil.Fetch(searchResultSelected.ResultItem);
			                             	var oldItem = MetaVideoEditorEvolved.UI.KernelSessionManager.SessionInstance.RealKernel.ItemCollection.ItemsList.First(media=>media.Id == this.currentItem.Id.ToString());
			                             	var newItem = mveEngine.Helper.UpdateItem(oldItem, i);
			                             	this.kernelHelper.SyncItemToEngine(newItem);
			                             	
			                             	DispatcherHelper.UIDispatcher.Invoke(new Action(()=>
			                             	                                                {
			                             	                                                	newItem.CopyToMediaUiEntity(currentItem);
			                             	                                                	currentItem.IsCheckedForUpdate = true;
			                             	                                                	currentItem.HasChanged = true;
			                             	                                                }));
			                             }), string.Empty).ShowDialog();
		}

		public string TitleSearch
		{
			get
			{
				return this.titleSearch;
			}

			set
			{
				this.titleSearch = value;
				RaisePropertyChanged("TitleSearch");
			}
		}

		public ObservableCollection<ManualSearchResultItem> SearchResults
		{
			get
			{
				return searchResults;
			}

			set
			{
				searchResults = value;
				RaisePropertyChanged("SearchResults");
			}
		}


		public ManualSearchResultItem SearchResultSelected
		{
			get
			{
				return searchResultSelected;
			}

			set
			{
				this.searchResultSelected = value;
				RaisePropertyChanged("SearchResultSelected");
			}
		}
		
		public string TitleWindow
		{
			get
			{
				return Kernel.Instance.GetString("SearchTitle");
			}
		}

		public ICommand SearchCommand { get; private set; }
		public ICommand ConfirmResultCommand { get; private set; }
		
		public void SearchMedia()
		{
			new WaitingWindow(new Action(() =>
			                             {
			                             	Item itemToSearch = new Item { Title = TitleSearch};
			                             	if (currentItem is MetaVideoEditorEvolved.UI.Entity.MediaItemBaseEntity) {
			                             		itemToSearch.Type = MetaVideoEditorEvolved.UI.Helper.EntityUiHelper.RetrieveEntityType(currentItem);
			                             	}
			                             	SearchResults = new ObservableCollection<ManualSearchResultItem>(from i in ProvidersUtil.FindPossible(itemToSearch)
			                             	                                                                 select new ManualSearchResultItem
			                             	                                                                 {
			                             	                                                                 	ResultItem = i,
			                             	                                                                 	IsChecked = false
			                             	                                                                 });
			                             }), string.Empty).ShowDialog();
		}
	}
	
	public class ManualSearchResultItem
	{
		public UI.Entity.PosterMediaItem Poster
		{
			get
			{
				return new UI.Entity.PosterMediaItem
				{
					Image = ResultItem.PrimaryImage.Image
				};
			}
		}
		
		public mveEngine.Item ResultItem { get; set; }
		
		public bool IsChecked { get; set; }
	}
}
